const app = getApp()
var common = require('../utils/common');
Page({
  data: {
    loading: true,
    page: 0,
    keyword:'',
    banner: [],
    imgheights: [],
    category: [],
    category_id: 0,
    ask: [],
  },
  //监听页面初次载入完成
  onLoad: function (event) {
    var that = this;
    that.getApi();
  },
  //上拉加载
  onReachBottom: function () {
    var that = this;
    that.setData({
      loading: true,
    });
    that.getApi();
  },
  //获取分类
  getApi: function () {
    var that = this;
    var parms = {
      signkey:'category',
    }
    app.api().Get('api/v1/bestbao/ask/category', parms, function (result) {
      if (result.code == 200) {
        that.setData({
          category: result.data,
        });
        that.getAds();
        that.getAsk(0);
      }
    })
  },
  //获取推荐
  getAds:function(){
    var that = this;
    var parms = {
      signkey: 'askads',
    }
    app.api().Get('api/v1/bestbao/ask/askAds', parms, function (result) {
      if (result.code == 200) {
        that.setData({
          banner: result.data,
        });
      }
    })
  },
  //获取API
  getAsk: function (category_id) {
    let that = this;
    if (that.data.loading) {
      var parms = {
        page: that.data.page + 1,
        category_id: category_id,
        keyword: that.data.keyword
      }
      app.api().Get('api/v1/bestbao/ask/index', parms, function (result) {
        if (result.code == 200) {
          var ask = that.data.ask;
          for (let i in result.data) {
            ask.push(result.data[i]);
          }
          that.setData({
            ask: ask,
            page: parms.page,
          });
        }
      })
      that.setData({
        loading: false,
      });
    }
  },
  //图片高度
  imageLoad: function (event) {
    this.setData({
      imgheights: common.autoimg(event)
    })
  },
  //点击表情
  onChange(event) {
    let category_id = event.detail.name;
    this.setData({
      loading: true,
      category_id: category_id,
      page: 0,
      ask: [],
    }) 
    this.getAsk(category_id);
  },
  //搜索
  onSearch(event) {
    this.setData({
      loading: true,
      keyword: event.detail,
      page: 0,
      ask: [],
    })
    this.getAsk(0)
  },
  //取消搜索
  onCancel() {
    this.setData({
      loading: true,
      category_id: 0,
      keyword:'',
      page: 0,
      ask: [],
    })
    this.getAsk(0)
  }
})